package core;

import java.util.ArrayList;

import mission.Mission;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import app.ServerApplication;

import system.AbstractSystem;
import tick.TickManager;

public class LogicThread extends Thread 
{

	private static final Logger logger = LoggerFactory.getLogger(LogicThread.class);  
	
	private long delay = 100l;
	
	private long date;
	
	public void start()
	{
		//开始记录时间
		date = System.currentTimeMillis();
		super.start();
	}
	
	public void run()
	{
		while(true)
		{
			//先执行所有的Tick
			TickManager.getInstance().extuce();
			//处理缓存的所有客户端消息
			handleMission();
			long time = System.currentTimeMillis() - date;
			date += time;
			long value = time - delay;
			if(value > 0)//出现Tick时间
			{
				if(value > delay)//差值大于的TICK时间，直接执行
				{
					logger.info("Server tick time : " + value);
					break;
				}
				else
				{
					sleepMethod(delay - value);
				}
			}
			else//没出现Tick
			{
				sleepMethod(delay + value);
			}
		}
	}
	
	private void sleepMethod(long time)
	{
		try 
		{
			if(time > 0)
			{
				sleep(time);
			} 
			else
			{
				sleep(delay);
			}
		}
		catch (InterruptedException e) 
		{
			logger.error("LogicThread sleepMethod sleep Thread error!!! " + e.getMessage());
		}
	}
	
	private void handleMission()
	{
		ArrayList<Mission> lst = MissionSaver.getInstance().getLst();
		int size = lst.size();
		AbstractSystem stm;
		for (int i = 0; i < size; i++) 
		{
			Mission mon = lst.remove(0);
			stm = ServerApplication.systems.get(mon.serverId);
			if(stm != null)
			{
				stm.handleMission(mon);
			}
		}
	}
	
}
